var mongoBase = require('../common/mongo-base');

module.exports = {
  admin: admin,
  login: login,
  checkLogin: checkLogin,
  logout: logout
};

function admin(req, res, next) {
  var userName = req.session.user.userName;
  var userId = req.session.user._id;
  var typeName = req.session.user.typeName;

  var query = {};
  var fields = {_id:1, data:1, artibodyTitle:1, pubDate:1, photo:1, key:1};
  var options = {sort:{data:1}, limit: 6};

  mongoBase.findData('home-banner', query, fields, options)

    .then(function(data) {

      var resData = {
        banners: data,
        userName: userName,
        userId: userId,
        typeName: typeName
      };
       res.render('admin', resData);
    })

    .catch(function(err){
      console.log(err);
    });

}

function login(req, res, next) {

  res.render('login');

}

function checkLogin(req, res, next) {
  var email = req.body.email;
  var password = req.body.password;

  var query = {email: email};
  var fields = {_id:1, userName:1, email:1, phone:1, typeName:1, password:1};

  mongoBase.findOneData('user-data', query, fields)

    .then(function(data) {
      if(data && data.email == email && data.password == password) {
        req.session.user = data;
        res.send({url:'/admin'});
      } else if(data && data.email == email){
        res.send({error: 2, message: '密码错误!'});
      } else {
        res.send({error: 1, message: '邮箱错误!'});
      }
    })

    .catch(function(err) {
      console.log(err);
    });

}

function logout(req, res, next) {

  req.session.user = null;

  res.redirect('/login');

}